import i18n from '@/locales'

const { t } = i18n.global

const oneMin = 60 * 1000;
const oneHour = 60 * oneMin;
const oneDay = 24 * oneHour;

function getTimes(remainTime, interval) {
  const times = Math.floor(remainTime / interval);
  return [times, remainTime % interval];
}

export function fnTimeToUse(time) {
  if (!time) {
    return '--';
  }
  let remainTime = time;
  let timeStr = '';
  let times = 0;
  if (remainTime >= oneDay) {
    [times, remainTime] = getTimes(remainTime, oneDay);
    timeStr += `${times}${t('common.day')}`;
  }
  if (remainTime >= oneHour) {
    [times, remainTime] = getTimes(remainTime, oneHour);
    timeStr += `${times}${t('common.hour')}`;
  }
  if (remainTime >= oneMin) {
    [times, remainTime] = getTimes(remainTime, oneMin);
    timeStr += `${times}${t('common.minute')}`;
  }
  timeStr += `${(remainTime / 1000).toFixed(2)}${t('common.second')}`;
  return timeStr;
}

function formatTwoDigit(val) {
  return val < 10 ? `0${val}` : val;
}

function getTimeDict(value) {
  const date = new Date(Number(value));
  return {
    year: date.getFullYear(),
    month: formatTwoDigit(date.getMonth() + 1),
    day: formatTwoDigit(date.getDate()),
    hour: formatTwoDigit(date.getHours()),
    min: formatTwoDigit(date.getMinutes()),
    second: formatTwoDigit(date.getSeconds()),
  };
}

// 时间戳转换成年月日，时分秒：2020-04-07 18:08:58
export function formatDateTime(value) {
  if (typeof value === 'undefined') {
    return '';
  }
  const time = getTimeDict(value);
  return `${time.year}-${time.month}-${time.day} ${time.hour}:${time.min}:${time.second}`;
}

export function abbFormatDate(value) {
  if (!value) {
    return '--';
  }
  const time = getTimeDict(value);
  const now = new Date();
  let str = `${time.hour}:${time.min}`;
  if (Number(time.day) < now.getDate()) {
    str = `${time.month}-${time.day} ${str}`;
  }
  return str;
}
